package com.yellowpage.nsp.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.yellowpage.white.util.ReadLog;

public class NspLogProcesser {

	private final static Properties properties = new Properties();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Calendar cal = new GregorianCalendar();
		cal.setTime(new Date());

		int hour = cal.get(Calendar.HOUR);
		
		cal.set(Calendar.HOUR, hour - 1);

		SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
		
		
		String zipFileName = sFormat.format(cal.getTime()) + ".zip";
		
		System.out.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger zipFileName:" + zipFileName);

		processLogFile(zipFileName);
		
		
		String o2oZipFileName = "o2o_" + sFormat.format(cal.getTime()) + ".zip";
		
		System.out.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger o2oZipFileName:" + o2oZipFileName);

		processO2OLogFile(o2oZipFileName);

	}

	public static void processLogFile(String zipFileName) {
		
		Connection conn = null;
		PreparedStatement pstmt = null;

		try {
			properties.load(new FileInputStream("/home/data/constants.properties"));

			String driver = properties.getProperty("jdbc.driverClassName");
			String url = properties.getProperty("jdbc.url");
			String username = properties.getProperty("jdbc.username");
			String password = properties.getProperty("jdbc.password");

			String log_file_dir = properties.getProperty("log_file_dir");

			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);

			String sql = " select a.SERVER_ID, a.LOG_DIR from NSP_SERVER a where  TYPE = 'NOR' AND STATUS != '1' ";
			pstmt = conn.prepareStatement(sql);

			ResultSet rs = pstmt.executeQuery();

			String serverId = "";
			String logDir = "";
			String zipPath = "";
			String logPath = "";

			while (rs.next()) {
				serverId = rs.getString("SERVER_ID");
				logDir = rs.getString("LOG_DIR");

				zipPath = log_file_dir + logDir + '/' + zipFileName;

				System.out.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger zipPath:"
								+ zipPath);

				logPath = unZip(zipPath);
				
				System.out.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger logPath:"
								+ logPath);
				
				
				if (!logPath.equals("")) {

					System.out.println("^^^^^^^^^^^^^^^^^^^^ savLogSum :" + serverId  + " : " + logPath);
					
					List<Map> list = ReadLog.BufferedReader(logPath);
					

					if (list.size() > 0) {
						
						String insertLogSumSql = "INSERT INTO NSP_LOG_SUM (`SERVER_ID`, `LOG_FILE_NAME`, `LOG_TIME`," +
								"  `REQUEST_TYPE`,  `RESPONSE_CODE`,  " +
								"  `COUNT`,   `STATUS`,  `CREATE_USER`,  `CREATE_TIME`)" +
								"     VALUES (?, ?, ?, ?, ?, ?, '1', 1, now())";
					    pstmt = conn.prepareStatement(insertLogSumSql);
					    
						for (Map sumMap : list) {
							
							pstmt.setInt(1, Integer.parseInt(serverId));
						    pstmt.setString(2, sumMap.get("logFileName").toString());
						    pstmt.setString(3, sumMap.get("logTime").toString());
						    pstmt.setString(4, sumMap.get("requestType").toString());
						    pstmt.setString(5, sumMap.get("responseCode").toString());
						    pstmt.setInt(6, Integer.parseInt(sumMap.get("count").toString())); 

							pstmt.addBatch();
						}
						
						pstmt.executeBatch();
					}					
				}

			}
			
			conn.close();
			pstmt.close();

		}catch (Exception e) {			
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
				if (pstmt != null)
					pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	
	
    public static void processO2OLogFile(String zipFileName) {
		
		Connection conn = null;
		PreparedStatement pstmt = null;

		try {
			properties.load(new FileInputStream("/home/data/constants.properties"));

			String driver = properties.getProperty("jdbc.driverClassName");
			String url = properties.getProperty("jdbc.url");
			String username = properties.getProperty("jdbc.username");
			String password = properties.getProperty("jdbc.password");

			String log_file_dir = properties.getProperty("log_file_dir");

			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);

			String sql = " select a.SERVER_ID, a.LOG_DIR from NSP_SERVER a where TYPE = 'O2O' AND STATUS != '1' ";
			pstmt = conn.prepareStatement(sql);

			ResultSet rs = pstmt.executeQuery();

			String serverId = "";
			String logDir = "";
			String zipPath = "";
			String logPath = "";

			while (rs.next()) {
				serverId = rs.getString("SERVER_ID");
				logDir = rs.getString("LOG_DIR");

				zipPath = log_file_dir + logDir + '/' + zipFileName;

				System.out.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger zipPath:"
								+ zipPath);

				logPath = unZip(zipPath);
				
				System.out.println("^^^^^^^^^^^^^^^^^^^^ getServerLoger logPath:"
								+ logPath);
				
				
				if (!logPath.equals("")) {

					System.out.println("^^^^^^^^^^^^^^^^^^^^ savLogSum :" + serverId  + " : " + logPath);
					
					List<Map> list = ReadLog.BufferedReader(logPath);
					

					if (list.size() > 0) {
						
						String insertLogSumSql = "INSERT INTO NSP_LOG_SUM_O2O (`SERVER_ID`, `LOG_FILE_NAME`, `LOG_TIME`," +
								"  `REQUEST_TYPE`,  `RESPONSE_CODE`,  " +
								"  `COUNT`,   `STATUS`,  `CREATE_USER`,  `CREATE_TIME`)" +
								"     VALUES (?, ?, ?, ?, ?, ?, '1', 1, now())";
					    pstmt = conn.prepareStatement(insertLogSumSql);
					    
						for (Map sumMap : list) {
							
							pstmt.setInt(1, Integer.parseInt(serverId));
						    pstmt.setString(2, sumMap.get("logFileName").toString());
						    pstmt.setString(3, sumMap.get("logTime").toString());
						    pstmt.setString(4, sumMap.get("requestType").toString());
						    pstmt.setString(5, sumMap.get("responseCode").toString());
						    pstmt.setInt(6, Integer.parseInt(sumMap.get("count").toString())); 

							pstmt.addBatch();
						}
						
						pstmt.executeBatch();
					}					
				}

			}
			
			conn.close();
			pstmt.close();

		}catch (Exception e) {			
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
				if (pstmt != null)
					pstmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public static String unZip(String path) {
		int buffer = 2048;

		String fileName = "";

		int count = -1;
		int index = -1;

		String savepath = "";
		boolean flag = false;

		savepath = path.substring(0, path.lastIndexOf("/")) + "/";

		try {
			BufferedOutputStream bos = null;
			ZipEntry entry = null;
			FileInputStream fis = new FileInputStream(path);
			ZipInputStream zis = new ZipInputStream(
					new BufferedInputStream(fis));

			while ((entry = zis.getNextEntry()) != null) {
				byte data[] = new byte[buffer];

				String temp = entry.getName();

				index = temp.lastIndexOf("/");
				if (index > -1)
					temp = temp.substring(index + 1);
				temp = savepath + temp;

				File f = new File(temp);
				f.createNewFile();

				fileName = temp;

				FileOutputStream fos = new FileOutputStream(f);
				bos = new BufferedOutputStream(fos, buffer);

				while ((count = zis.read(data, 0, buffer)) != -1) {
					bos.write(data, 0, count);
				}

				bos.flush();
				bos.close();
			}

			zis.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return fileName;
	}

}
